<?php

namespace app\wechat\models;

use app\wechat\core\BaseModel;
use cm;
use Yii;
use yii\helpers\Url;

class SiteModel extends BaseModel
{
	/*
	*所有站点
	*/
	public function actionAll(){
		$this->getData();
	}

	public function actionSearch(){
		$key = Cm::$req->post('key', ['null', 'empty', 'default' => '']);
		$this->getData($key);
	}

	/*
	*获取站点数据
	*/
	private function getData($key = ''){
		$where = " 1=1 ";
		if(!empty($key)){
			$where = $this->searchWhere($where,$key);
		}
		$sql = "SELECT aa.name,aa.sid,aa.cid,aa.type,aa.firstchar,aa.is_hot FROM ( 
					SELECT name,full_name,'' AS full_pinyin,'' AS short_pinyin,id AS sid,0 AS cid,'site' AS type,firstchar,is_hot FROM site WHERE status=1
					UNION ALL
					SELECT name,full_name,full_pinyin,short_pinyin,0 AS sid,id AS cid,'city' AS type,firstchar,is_hot FROM open_city WHERE status=1
				) aa WHERE {$where} ORDER BY aa.firstchar ASC,aa.is_hot DESC";
		$resdata = Cm::$db->all($sql);
		$data = $this->organizeData($resdata);	
		Cm::$res->susess($data);
	}

	/*
	*处理搜索条件
	*/
	private function searchWhere($where,$key){
		$smallletter = $this->smallletter();
		$capitalletter = $this->capitalletter();
		if(in_array($key, $smallletter)){
			$key = strtoupper($key);
			$where .= " AND aa.firstchar='{$key}' ";
			return $where;
		}
		if(in_array($key, $capitalletter)){
			$where .= " AND aa.firstchar='{$key}' ";
			return $where;
		}
		/*去空格判断为中文还是拼音*/
		$nospacestr = str_replace(' ', '', $key);
		if(!preg_match("/^[a-zA-Z]*$/", $nospacestr)){
			$where .= " AND (aa.name LIKE '%{$nospacestr}%' or aa.full_name LIKE '%{$nospacestr}%') ";
			return $where;
		}else{
			$smallletterkey = strtolower($nospacestr);
			$capitalletterkey = strtoupper($nospacestr);
			$where .= " AND (replace(aa.full_pinyin,' ','') LIKE '%{$smallletterkey}%' or replace(aa.short_pinyin,' ','') LIKE '%{$capitalletterkey}%')";
		}
		return $where;
	}

	/*
	* 整理数据
	*/
	private function organizeData($resdata){
		$data = ['first'=>[],'city'=>[]];
		if(!empty($resdata)){
			$str = "";
			foreach ($resdata as $key => $value) {
				if($value['firstchar'] != $str){
					$str = $value['firstchar'];
					$data['first'][] = $str;
					$data['city'][] = ['title'=>$str,'lists'=>[]];
				}
				$num = count($data['city'])-1;
				$data['city'][$num]['lists'][] = $value;
			}
		} 	
		return $data;
	}
}